import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Tag, Space, Modal, message } from 'antd';
import React, { useRef, useState } from 'react';

type Post = {
  id: number;
  title: string;
  author: string;
  authorId: number;
  createTime: string;
  status: 'published' | 'unpublished' | 'pending';
  viewCount: number;
  likeCount: number;
  commentCount: number;
};

const statusMap = {
  published: { text: '已发布', color: 'green' },
  unpublished: { text: '未发布', color: 'orange' },
  pending: { text: '待审核', color: 'blue' },
};

const Posts: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRows, setSelectedRows] = useState<Post[]>([]);

  // 模拟数据
  const mockPosts: Post[] = Array.from({ length: 50 }).map((_, index) => ({
    id: index + 1,
    title: `露营体验分享 ${index + 1}`,
    author: `用户${Math.floor(Math.random() * 1000)}`,
    authorId: Math.floor(Math.random() * 1000),
    createTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString(),
    status: ['published', 'unpublished', 'pending'][Math.floor(Math.random() * 3)] as any,
    viewCount: Math.floor(Math.random() * 10000),
    likeCount: Math.floor(Math.random() * 1000),
    commentCount: Math.floor(Math.random() * 100),
  }));

  // 模拟请求数据
  const fetchPosts = async (params: any) => {
    const { current, pageSize, title, status, author } = params;
    
    let filteredData = [...mockPosts];
    
    if (title) {
      filteredData = filteredData.filter(item => item.title.includes(title));
    }
    
    if (status) {
      filteredData = filteredData.filter(item => item.status === status);
    }
    
    if (author) {
      filteredData = filteredData.filter(item => item.author.includes(author));
    }
    
    const startIndex = (current - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const data = filteredData.slice(startIndex, endIndex);
    
    return {
      data,
      success: true,
      total: filteredData.length,
    };
  };

  const handlePublish = (ids: number[], isPublish: boolean) => {
    Modal.confirm({
      title: `确定要${isPublish ? '发布' : '取消发布'}选中的作品吗？`,
      content: '此操作将改变作品的发布状态',
      onOk: () => {
        message.success(`已${isPublish ? '发布' : '取消发布'}选中的作品`);
        actionRef.current?.reload();
      },
    });
  };

  const handleDelete = (ids: number[]) => {
    Modal.confirm({
      title: '确定要删除选中的作品吗？',
      content: '此操作不可恢复',
      onOk: () => {
        message.success('已删除选中的作品');
        actionRef.current?.reload();
      },
    });
  };

  const columns: ProColumns<Post>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '作者',
      dataIndex: 'author',
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        published: { text: '已发布', status: 'Success' },
        unpublished: { text: '未发布', status: 'Warning' },
        pending: { text: '待审核', status: 'Processing' },
      },
    },
    {
      title: '浏览量',
      dataIndex: 'viewCount',
      search: false,
    },
    {
      title: '点赞数',
      dataIndex: 'likeCount',
      search: false,
    },
    {
      title: '评论数',
      dataIndex: 'commentCount',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a key="edit" onClick={() => message.info(`编辑作品 ${record.id}`)}>
          编辑
        </a>,
        <a
          key="publish"
          onClick={() => handlePublish([record.id], record.status !== 'published')}
        >
          {record.status === 'published' ? '取消发布' : '发布'}
        </a>,
        <a key="delete" onClick={() => handleDelete([record.id])}>
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<Post>
        headerTitle="作品列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            onClick={() => message.info('新建作品')}
            icon={<PlusOutlined />}
          >
            新建
          </Button>,
        ]}
        request={fetchPosts}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space>
            <span>已选 {selectedRowKeys.length} 项</span>
            <a onClick={onCleanSelected}>取消选择</a>
          </Space>
        )}
        tableAlertOptionRender={() => (
          <Space>
            <Button
              onClick={() => handlePublish(
                selectedRows.map(row => row.id),
                true
              )}
            >
              批量发布
            </Button>
            <Button
              onClick={() => handlePublish(
                selectedRows.map(row => row.id),
                false
              )}
            >
              批量取消发布
            </Button>
            <Button
              danger
              onClick={() => handleDelete(selectedRows.map(row => row.id))}
            >
              批量删除
            </Button>
          </Space>
        )}
      />
    </PageContainer>
  );
};

export default Posts; 